Return to doc.sitecore.com

Valid for Sitecore 5.2, 5.3
How can I safely place JavaScript code into the OnClick attribute of an tag?

In general, the use of javascript inside HTML code is not good practice. As an alternative, Sitecore V5 provides you with special field type for use with Javascript links.  This is called the Link field. The following steps describe how to use this field type:

  1. In the Template Editor, create a field in an appropriate Template and set the field's data type to Link.
  2. In Content Editor, open an Item based on the Template.
  3. Locate the Link field, and choose the Insert JavaScript link from the dropdown menu provided by the Insert Link button.
  4. This will start a Wizard in which you may insert the desired JavaScript code. 

     
  5. Remember to modify any appropriate XSL renderings in order to output the link field.  For example:

    <p><sc:link field="link"/></p>

In this case javascript link will be inserted into page with onClick attribute. Please have a look at the example result:

<p><a title="text" href="#" onclick="javascript:window.open();return false;">link</a></p>

Entering Javascript in the Rich Text Editor

At the moment, due to a known issue, the HTML editor does not save the onClick attribute included in an <a> tag. You are able to put javascript code into href attribute, but it is sometimes necessary to put javascript code into the onClick attribute of an <a> tag.

In these cases, you can use the Publish Replacements facility to put javascript code into onClick attribute.

For this you should enable a Replacer in the web.config and add a replecement that will read javascript code from the href attribute and replace it with an onClick attribute.

<replacers>

  <replacer mode="on" id="publish" type="Sitecore.Text.Replacer, Sitecore.Kernel" singleInstance="true">

    <param desc="name">$(id)</param>

    <replacements hint="raw:AddReplacement">

      <regex find="<a href="javascript:(.*)">(.*)</a>"

             replaceWith="<a href="javascript:;" onClick="$1">$2</a>"

             ignoreCase="true" />

    </replacements>

  </replacer>

</replacers>

Once you have configured this replacer, Sitecore will replace the link:

<a href="javascript:window.open()">Open Window</a>

to

<a href="javascript:void(0);" onClick="window.open()">Open Window</a>